package com.xpoint.backend.filter;

import com.alibaba.fastjson.JSON;
import com.xpoint.backend.common.BaseContext;
import com.xpoint.backend.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();//一个工具类

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
//        response.setCharacterEncoding("utf-8");
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=UTF-8");
//        response.getWriter().println("你被拦截了，兄弟");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//        获取当前网页的url
        String requestURI = httpServletRequest.getRequestURI();
        String[] strings = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/**/common/**",
                "/user/register"
        };//默认放行的路径

        boolean check = check(requestURI, strings);
        if (check) {
//            是默认路径里面的话就放行
            filterChain.doFilter(request, response);
            return;
        }
//        获取登录以后的session
        Long employee = (Long) ((HttpServletRequest) request).getSession().getAttribute("employee");
        Long userId = (Long) ((HttpServletRequest) request).getSession().getAttribute("userId");
//         通过判断session，是否登录过，如果已登录，就直接放行
        if (employee != null) {
//            将登录的id设置到当前线程局部变量
            BaseContext.setCurrentId(employee);
//            放行
            filterChain.doFilter(request, response);
            return;
        }

        if (userId!=null){
            //            将登录的id设置到当前线程局部变量
            BaseContext.setCurrentId(userId);
//            放行
            filterChain.doFilter(request, response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));  //写入json数据，R.error前端处理
        return;
    }

    private boolean check(String requestURI, String[] strings) {
//        遍历默认放行的路径，
        for (String string : strings) {
            boolean match = ANT_PATH_MATCHER.match(string, requestURI); //包含在默认放行的路径，包含的话是true，否则是false
            if (match) {
                return true;//返回true
            }
        }
        return false;//否则返回false
    }

}
